package com.wushi.lenovo.asia5b.app_ui.profile.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.ListPopupWindow;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import com.mvp.base.BaseMvpActivity;
import com.mvp.base.model.ResultModel;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.profile.mvpview.NewAddressActivityView;
import com.wushi.lenovo.asia5b.app_di.profile.presenter.NewAddressActivityPresenter;
import com.wushi.lenovo.asia5b.app_event.NewAddressEvent;
import com.wushi.lenovo.asia5b.app_model.other.PopupItemTextIml;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_model.profile.AddressModel;
import com.wushi.lenovo.asia5b.app_model.profile.CountryModel;
import com.wushi.lenovo.asia5b.app_model.profile.PostCodeModel;
import com.wushi.lenovo.asia5b.app_model.profile.ProvinceOrCityModel;
import com.wushi.lenovo.asia5b.app_utils.WToastHelper;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupListAdapter;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupWindowHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Function;

/**
 * 添加收货地址
 */
public class NewAddressActivity extends BaseMvpActivity<
        NewAddressActivityView, NewAddressActivityPresenter> implements NewAddressActivityView, TextWatcher {

    @BindView(R.id.tv_title_titletext)
    TextView tv_title_titletext;
    @BindView(R.id.et_newaddress_name)
    EditText et_newaddress_name;
    @BindView(R.id.tv_newaddress_name_error)
    TextView tv_newaddress_name_error;
    @BindView(R.id.et_newaddress_buildingname)
    EditText et_newaddress_buildingname;
    @BindView(R.id.tv_newaddress_callingcode)
    TextView tv_newaddress_callingcode;
    @BindView(R.id.et_newaddress_mobile)
    EditText et_newaddress_mobile;
    @BindView(R.id.tv_newaddress_mobile_error)
    TextView tv_newaddress_mobile_error;
    @BindView(R.id.tv_newaddress_country)
    TextView tv_newaddress_country;
    @BindView(R.id.tv_newaddress_country_error)
    TextView tv_newaddress_country_error;
    @BindView(R.id.et_newaddress_detail)
    EditText et_newaddress_detail;
    @BindView(R.id.tv_newaddress_detail_error)
    TextView tv_newaddress_detail_error;
    @BindView(R.id.tv_newaddress_state)
    TextView tv_newaddress_province;
    @BindView(R.id.tv_newaddress_state_error)
    TextView tv_newaddress_state_error;
    @BindView(R.id.tv_newaddress_city)
    TextView tv_newaddress_city;
    @BindView(R.id.tv_newaddress_post)
    TextView tv_newaddress_post;
    @BindView(R.id.tv_newaddress_city_error)
    TextView tv_newaddress_city_error;
    @BindView(R.id.tv_newaddress_postcode_error)
    TextView tv_newaddress_postcode_error;
    @BindView(R.id.sw_newaddress_ship)
    Switch sw_newaddress_ship;
    @BindView(R.id.sw_newaddress_bill)
    Switch sw_newaddress_bill;
    @BindView(R.id.bt_newaddress_save)
    Button bt_newaddress_save;
    @BindView(R.id.bt_newaddress_cancle)
    Button bt_newaddress_cancle;
    private AddressModel model;
    private PopupListAdapter<PopupItemTextIml> postAdapter;
    private PopupListAdapter<ProvinceOrCityModel> cityAdapter;
    private PopupListAdapter<ProvinceOrCityModel> provinceAdapter;
    private PopupListAdapter<CountryModel> countryAdapter;
    private ListPopupWindow popupWindowCountry;
    private ListPopupWindow popupWindowProvince;
    private ListPopupWindow popupWindowCity;
    private ListPopupWindow popupWindowPost;
    private boolean isOrderPayment;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        tv_newaddress_country_error.setVisibility(View.GONE);
        tv_newaddress_city_error.setVisibility(View.GONE);
        tv_newaddress_state_error.setVisibility(View.GONE);
        tv_newaddress_name_error.setVisibility(View.GONE);
        tv_newaddress_postcode_error.setVisibility(View.GONE);
        tv_newaddress_mobile_error.setVisibility(View.GONE);
        tv_newaddress_detail_error.setVisibility(View.GONE);
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_newaddress;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model = (AddressModel) getIntent().getSerializableExtra(CommonConstant.ADDRESS_MODEL);
        isOrderPayment = getIntent().getBooleanExtra("OrderPayment", false);

        initView();

        initData();

        initEvent();
    }

    @Override
    protected void initView() {


        countryAdapter = new PopupListAdapter<>(this, R.layout.item_popupitem_newaddress_adapter);
        popupWindowCountry = PopupWindowHelper.getListPopupWindow(this, countryAdapter
                , tv_newaddress_country, ListPopupWindow.WRAP_CONTENT);

        provinceAdapter = new PopupListAdapter<>(this, R.layout.item_popupitem_newaddress_adapter);
        popupWindowProvince = PopupWindowHelper.getListPopupWindow(this, provinceAdapter
                , tv_newaddress_province, ListPopupWindow.WRAP_CONTENT);

        cityAdapter = new PopupListAdapter<>(this, R.layout.item_popupitem_newaddress_adapter);
        popupWindowCity = PopupWindowHelper.getListPopupWindow(this, cityAdapter
                , tv_newaddress_city, ListPopupWindow.WRAP_CONTENT);

        postAdapter = new PopupListAdapter<>(this, R.layout.item_popupitem_newaddress_adapter);
        popupWindowPost = PopupWindowHelper.getListPopupWindow(this, postAdapter
                , tv_newaddress_post, ListPopupWindow.WRAP_CONTENT);

        setView();

    }

    private void setView() {
        try {

            if (model != null) {
                tv_title_titletext.setText(getString(R.string.newaddress_titlename_edit));

                //收件人
                et_newaddress_name.setText(model.getContact_name());

                //标签
                et_newaddress_buildingname.setText(model.getBuilding_name());

                //电话
                //区号
                tv_newaddress_callingcode.setText("+" + model.getCalling_code() + "");
                et_newaddress_mobile.setText(model.getContact_no());

                //国家
                tv_newaddress_country.setText(model.getCountry());

                //省
                tv_newaddress_province.setText(model.getState());

                //城市
                tv_newaddress_city.setText(model.getCity());

                //详细地址
                et_newaddress_detail.setText(model.getAddress());

                //邮编
                tv_newaddress_post.setText(model.getPostcode_no());

                sw_newaddress_ship.setChecked(model.isShipAddressDefault());
                sw_newaddress_bill.setChecked(model.isBillAddressDefault());
            } else {
                tv_title_titletext.setText(getString(R.string.newaddress_titlename_new));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initData() {

        if (model == null) {
            getPresenter().getCountrys();
        } else {
            getPresenter().getCountrysStateCityPost(model);
        }

    }

    /**
     * 新建地址
     */
    private Map<String, Object> getMap() {
//        if (GlobalValue.isDebug) {
//            et_newaddress_detail.setText("lala");
//            et_newaddress_name.setText("lala");
//            et_newaddress_buildingname.setText("lala");
//        }

        try {
            boolean b = false;
            //address_id
            //address详细地址
            String address = et_newaddress_detail.getText().toString().trim();
            if (TextUtils.isEmpty(address)) {
                b = true;
                tv_newaddress_detail_error.setVisibility(View.VISIBLE);
            }
            //contact_name收件人
            String contact_name = et_newaddress_name.getText().toString().trim();
            if (TextUtils.isEmpty(contact_name)) {
                b = true;
                tv_newaddress_name_error.setVisibility(View.VISIBLE);
            }
            //building_name标签名称
            String building_name = et_newaddress_buildingname.getText().toString().trim();
            //calling_code
            String calling_code = tv_newaddress_callingcode.getText().toString().trim();
            //contact_no
            String contact_no = et_newaddress_mobile.getText().toString().trim();
            if (TextUtils.isEmpty(contact_no)) {
                tv_newaddress_mobile_error.setVisibility(View.VISIBLE);
                b = true;
            }
            //postcode_no
            String postcode_no = tv_newaddress_post.getText().toString().trim();
            if (TextUtils.isEmpty(postcode_no)) {
                tv_newaddress_postcode_error.setVisibility(View.VISIBLE);
                b = true;
            }
            //other_postcode
            //state_id
            int state_id = 0;
            ProvinceOrCityModel proviceModel = provinceAdapter.getSelectItem();
            if (proviceModel != null) {
                state_id = proviceModel.getId();
            }
            if (state_id <= 0) {
                tv_newaddress_state_error.setVisibility(View.VISIBLE);
                b = true;
            }
            //city_id
            ProvinceOrCityModel cityModel = cityAdapter.getSelectItem();
            int city_id = 0;
            if (cityModel != null) {
                city_id = cityModel.getId();
            }
            if (city_id <= 0) {
                tv_newaddress_city_error.setVisibility(View.VISIBLE);
                b = true;
            }
            //other_city
            //member_id
            String member_id = UserInfo.getMemberId() + "";
            //country_id
            int country_id = 0;
            CountryModel countryModel = countryAdapter.getSelectItem();
            if (countryModel != null) {
                country_id = countryModel.getId();
            }
            if (country_id <= 0) {
                tv_newaddress_country_error.setVisibility(View.VISIBLE);
                b = true;
            }
            //default_ship_address

            if (b) {
                return null;
            }
            Map<String, Object> map = MapHelper.newHashMap();
            map.put("address", address);
            map.put("contact_name", contact_name);
            map.put("building_name", building_name);
            map.put("calling_code", calling_code);
            map.put("contact_no", contact_no);
            map.put("postcode_no", postcode_no);
//            map.put("other_postcode", postcode_no);//不需要
            map.put("state_id", state_id);
            map.put("city_id", city_id);
//            map.put("other_city", city_id);//不需要
            map.put("member_id", member_id);
            map.put("country_id", country_id);
            map.put("default_ship_address", sw_newaddress_ship.isChecked() ? "1" : "0");
            //default_bill_address
            map.put("default_bill_address", sw_newaddress_bill.isChecked() ? "1" : "0");
            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void initEvent() {
        et_newaddress_detail.addTextChangedListener(this);
        et_newaddress_name.addTextChangedListener(this);
        et_newaddress_mobile.addTextChangedListener(this);
        tv_newaddress_country.addTextChangedListener(this);
        tv_newaddress_province.addTextChangedListener(this);
        tv_newaddress_city.addTextChangedListener(this);

        popupWindowCountry.setOnItemClickListener((parent, view, position, id) -> {
            popupWindowCountry.dismiss();
            if (position == countryAdapter.getSelectPosition()) {//如果是选择相同就不继续执行
                return;
            }
            countryAdapter.setSelectPosition(position);
            CountryModel model = countryAdapter.getSelectItem();
            if (model != null) {
                //设置item
                tv_newaddress_country.setText(model.getName());
                tv_newaddress_callingcode.setText("+" + model.getCalling_code());

                //清空省,市
                clearStateData();
                clearCityData();
                clearPostData();
                getPresenter().getProvincesById(model.getId());

            }
        });

        popupWindowProvince.setOnItemClickListener((parent, view, position, id) -> {
            popupWindowProvince.dismiss();
            if (position == provinceAdapter.getSelectPosition()) {//如果是选择相同就不继续执行
                return;
            }
            provinceAdapter.setSelectPosition(position);
            ProvinceOrCityModel model = provinceAdapter.getSelectItem();
            if (model != null) {
                //设置item
                tv_newaddress_province.setText(model.getName());

                //清空市
                clearCityData();
                clearPostData();
                getPresenter().getCityesById(model.getId());

            }
        });

        popupWindowCity.setOnItemClickListener((parent, view, position, id) -> {
            popupWindowCity.dismiss();
            if (position == cityAdapter.getSelectPosition()) {//如果是选择相同就不继续执行
                return;
            }
            cityAdapter.setSelectPosition(position);
            ProvinceOrCityModel model = cityAdapter.getSelectItem();
            if (model != null) {
                //设置item
                tv_newaddress_city.setText(model.getName());

                //清空邮编
                clearPostData();

                getPresenter().getPostCodeByCity(model.getId());

            }
        });

        popupWindowPost.setOnItemClickListener((parent, view, position, id) -> {
            popupWindowPost.dismiss();
            postAdapter.setSelectPosition(position);
            //设置item
            tv_newaddress_post.setText(postAdapter.getSelectItemText());

        });
    }

    //清空国家数据
    private void clearCountryData() {
        countryAdapter.setDatas(null);
        tv_newaddress_country.setText("");
    }

    //清空省数据
    private void clearStateData() {
        provinceAdapter.setDatas(null);
        tv_newaddress_province.setText("");
    }

    //清空城市数据
    private void clearCityData() {
        cityAdapter.setDatas(null);
        tv_newaddress_city.setText("");
    }

    //清空邮编数据
    private void clearPostData() {
        postAdapter.setDatas(null);
        tv_newaddress_post.setText("");
    }

    @Override
    @OnClick({
            R.id.bt_newaddress_save,
            R.id.bt_newaddress_cancle,
            R.id.tv_newaddress_country,
            R.id.tv_newaddress_post,
            R.id.tv_newaddress_state,
            R.id.tv_newaddress_city
    })
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_newaddress_cancle:
                finish();
                break;
            case R.id.bt_newaddress_save://提交
                Map<String, Object> map = getMap();
                if (map != null) {
                    if (model == null) {//新增地址
                        getPresenter().addAddress(map, sw_newaddress_ship.isChecked(), sw_newaddress_bill.isChecked());
                    } else {//保存修改地址
                        map.put("address_id", model.getId() + "");
                        getPresenter().updateAddress(model, map, sw_newaddress_ship.isChecked(), sw_newaddress_bill.isChecked());
                    }
                }

                break;
            case R.id.tv_newaddress_country: {
                PopupWindowHelper.showPopupWindow(popupWindowCountry);
            }
            break;
            case R.id.tv_newaddress_state: {
                PopupWindowHelper.showPopupWindow(popupWindowProvince);
            }
            break;
            case R.id.tv_newaddress_city: {
                PopupWindowHelper.showPopupWindow(popupWindowCity);
            }
            break;
            case R.id.tv_newaddress_post: {
                PopupWindowHelper.showPopupWindow(popupWindowPost);
            }
            break;
            default:
                break;
        }
    }

    @Override
    public void getCountrysResult(List<CountryModel> countryModels) {
        countryAdapter.setDatas(countryModels);
    }

    @Override
    public void getProvincesResult(ResultModel<List<ProvinceOrCityModel>> resultModel) {
        if (resultModel.isSuccess()) {
            provinceAdapter.setDatas(resultModel.getData());
        }
    }

    @Override
    public void getCityesResult(ResultModel<List<ProvinceOrCityModel>> resultModel) {
        if (resultModel.isSuccess()) {
            cityAdapter.setDatas(resultModel.getData());
        }
    }

    @Override
    public void getPostCodeByCityResult(ResultModel<PostCodeModel> resultModel) {

        PostCodeModel postCodeModel = resultModel.getData();
        if (resultModel.isSuccess() && postCodeModel != null) {
            Observable.just(postCodeModel)
                    .map(new Function<PostCodeModel, List<String>>() {
                        @Override
                        public List<String> apply(PostCodeModel postCodeModel) throws Exception {
                            return Arrays.asList(postCodeModel.getCode().split(","));
                        }
                    })
                    .subscribe(strings -> {
                        List<PopupItemTextIml> list = new ArrayList<>();
                        for (String string : strings) {
                            list.add(new PopupItemTextIml(string));
                        }
                        postAdapter.setDatas(list);
                    }, throwable -> {
                        throwable.printStackTrace();
                    });
        }
    }

    @Override
    public void getCountrysStateCityPostResult(List<CountryModel> countrys, List<ProvinceOrCityModel> provinces, List<ProvinceOrCityModel> cityes, PostCodeModel postCodeByCity) {
        countryAdapter.setDatas(countrys);
        if (countrys != null) {
            for (int i = 0; i < countrys.size(); i++) {
                CountryModel countryModel = countrys.get(i);
                if (countryModel.getId() == model.getCountry_id()) {
                    countryAdapter.setSelectPosition(i);
                    break;
                }
            }
        }
        provinceAdapter.setDatas(provinces);
        if (provinces != null) {
            for (int i = 0; i < provinces.size(); i++) {
                ProvinceOrCityModel provinceOrCityModel = provinces.get(i);
                if (provinceOrCityModel.getId() == model.getState_id()) {
                    provinceAdapter.setSelectPosition(i);
                    break;
                }
            }
        }
        cityAdapter.setDatas(cityes);
        if (cityes != null) {
            for (int i = 0; i < cityes.size(); i++) {
                ProvinceOrCityModel provinceOrCityModel = cityes.get(i);
                if (provinceOrCityModel.getId() == model.getCity_id()) {
                    cityAdapter.setSelectPosition(i);
                    break;
                }
            }
        }
        if (postCodeByCity != null) {
            Observable.just(postCodeByCity)
                    .map(new Function<PostCodeModel, List<String>>() {
                        @Override
                        public List<String> apply(PostCodeModel postCodeModel) throws Exception {
                            return Arrays.asList(postCodeModel.getCode().split(","));
                        }
                    })
                    .subscribe(strings -> {
                        List<PopupItemTextIml> list = new ArrayList<>();
                        for (String string : strings) {
                            list.add(new PopupItemTextIml(string));
                        }
                        postAdapter.setDatas(list);
                        for (int i = 0; i < list.size(); i++) {
                            if (TextUtils.equals(list.get(i).getText(), model.getPostcode_no())) {
                                postAdapter.setSelectPosition(i);
                                break;
                            }
                        }
                    }, throwable -> {
                        throwable.printStackTrace();
                    });
        }

    }

    @Override
    public void addAddressResult(ResultModel resultModel, boolean isShipAddressDefault, boolean isBillAddressDefault) {
        if (resultModel.isSuccess()) {
            EventBus.getDefault().post(new NewAddressEvent());

            WToastHelper.showContentView(this, R.string.newaddress_addsuccess);

            if (isOrderPayment) {
                startActivity(new Intent(this, ChangeAddressActivity.class));
            }
            finish();
        }
    }

    @Override
    public void updateAddressResult(ResultModel resultModel, boolean isShipAddressDefault, boolean isBillAddressDefault) {
        if (resultModel.isSuccess()) {
            EventBus.getDefault().post(new NewAddressEvent());
            WToastHelper.showContentView(this, R.string.newaddress_updatesuccess);
            finish();
        }
    }


}
